package cn.itcast.netty.c5;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class Client3 {
    public static void main(String[] args) {
//        fill10Bytes('1',2);
//        fill10Bytes('6',5);
//        fill10Bytes('7',10);
        send();
    }

    public static StringBuilder makeString(char c,int len){
        final StringBuilder stringBuilder = new StringBuilder(len + 2);
        for (int i = 0; i < len; i++) {
            stringBuilder.append(c);
        }
        stringBuilder.append("\n");
        return stringBuilder;
    }

    private static void send() {
        final NioEventLoopGroup worker = new NioEventLoopGroup();
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(worker);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        //channel建立成功后，会触发active事件
                        final ByteBuf buf = ctx.alloc().buffer();
                        char c = '0';
                        final Random random = new Random();
                        for (int i = 0; i < 10; i++) {
                            final byte[] bytes = makeString(c,random.nextInt(256)+1).toString().getBytes();
                            c++;
                            buf.writeBytes(bytes);
                        }
                        ctx.writeAndFlush(buf);
                    }
                });
            }
        });
        try {
            final ChannelFuture channelFuture = bootstrap.connect("localhost", 8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("client error",e);
        }finally {
            worker.shutdownGracefully();
        }
    }

}
